<template>
  <div class="exam-page">
    <!-- 标题 -->
    <div class="exam-header">
      <h1>{{ examInfo.title || "考试" }}</h1>
    </div>

    <!-- 信息栏 -->
    <div class="exam-info">
      <div class="info-item">
        <span>开始日期</span>
        <span>{{ examInfo.startTime }}</span>
      </div>
      <div class="info-item">
        <span>截止日期</span>
        <span>{{ examInfo.endTime }}</span>
      </div>
      <div class="info-item">
        <span>考试时长</span>
        <span>{{ examInfo.duration }}分钟</span>
      </div>
      <div class="info-item">
        <span>培训项目</span>
        <span>{{ examInfo.trainingProject }}</span>
      </div>
      <div class="info-item">
        <span>考试须知</span>
        <span>{{ examInfo.notice }}</span>
      </div>
    </div>

    <!-- 试题区域 -->
    <div class="exam-content">
      <!-- 单选题 -->
     <div class="question-section" v-if="singleQuestions.length > 0">
        <h3>一 单选题</h3>
        <div
          class="question-item"
          v-for="(question, index) in singleQuestions"
          :key="question.id"
        >
          <div class="question-text">{{ index + 1 }}. {{ question.text }}</div>
          <div class="options">
            <label
              v-for="option in question.options"
              :key="option.id"
              class="option-label"
            >
              <input
                type="radio"
                :name="'single-' + question.id"
                :value="option.value"
                :checked="userAnswers.single[index] === option.value"
                @change="handleSingleChange(index, option.value)"
              />
              {{ option.label }}
            </label>
          </div>
        </div>
      </div>

      <!-- 多选题 -->
     <div class="question-section" v-if="multipleQuestions.length > 0">
        <h3>二 多选题</h3>
        <div
          class="question-item"
          v-for="(question, index) in multipleQuestions"
          :key="question.id"
        >
          <div class="question-text">{{ index + 1 }}. {{ question.text }}</div>
          <div class="options">
            <label
              v-for="option in question.options"
              :key="option.id"
              class="option-label"
            >
              <input
                type="checkbox"
                :name="'multiple-' + question.id"
                :value="option.value"
                :checked="
                  userAnswers.multiple[index] &&
                  userAnswers.multiple[index].includes(option.value)
                "
                @change="handleMultipleChange(index, option.value)"
              />
              {{ option.label }}
            </label>
          </div>
        </div>
      </div>

      <!-- 判断题 -->
     <div class="question-section" v-if="judgmentQuestions.length > 0">
        <h3>三 判断题</h3>
        <div
          class="question-item"
          v-for="(question, index) in judgmentQuestions"
          :key="question.id"
        >
          <div class="question-text">{{ index + 1 }}. {{ question.text }}</div>
          <div class="options">
            <label
              v-for="option in question.options"
              :key="option.id"
              class="option-label"
            >
              <input
                type="radio"
                :name="'judgment-' + question.id"
                :value="option.value"
                :checked="userAnswers.judgment[index] === option.value"
                @change="handleJudgmentChange(index, option.value)"
              />
              {{ option.label }}
            </label>
          </div>
        </div>
      </div>
    </div>

    <!-- 提交按钮 -->
    <div class="submit-container">
      <button class="submit-btn" @click="submitExam">提交</button>
    </div>
  </div>
</template>
<script>
import { classExam, saveExamResult } from "@/api/examination/portalExam";

export default {
  name: "PortalExam",
  data() {
    return {
      examInfo: {}, // 存储考试信息
      singleQuestions: [],
      multipleQuestions: [],
      judgmentQuestions: [],
      userAnswers: {
        single: {},
        multiple: {},
        judgment: {},
      },
      //提交的学生id
      tempStudentId: null,
      //提交的试卷id
      tempExamPaperId: null,
      // 用于保存定时器ID
      examTimer: null,
      // 剩余时间（毫秒）
      // timeRemaining: 0,
    };
  },
  async created() {
    this.loadExamData();
  },
  methods: {
    handleSingleChange(questionIndex, answer) {
      this.userAnswers.single[questionIndex] = answer;
      localStorage.setItem("examAnswers", JSON.stringify(this.userAnswers));
    },

    handleMultipleChange(questionIndex, answer) {
      if (!this.userAnswers.multiple[questionIndex]) {
        this.userAnswers.multiple[questionIndex] = [];
        localStorage.setItem("examAnswers", JSON.stringify(this.userAnswers));
      }
      const index = this.userAnswers.multiple[questionIndex].indexOf(answer);
      if (index === -1) {
        this.userAnswers.multiple[questionIndex].push(answer);
        localStorage.setItem("examAnswers", JSON.stringify(this.userAnswers));
      } else {
        this.userAnswers.multiple[questionIndex].splice(index, 1);
        localStorage.setItem("examAnswers", JSON.stringify(this.userAnswers));
      }
    },

    handleJudgmentChange(questionIndex, answer) {
      this.userAnswers.judgment[questionIndex] = answer;
      localStorage.setItem("examAnswers", JSON.stringify(this.userAnswers));
    },
    //调用接口给考试赋值
    loadExamData() {
      var params = { trainingClassId: "3" };
      const trainingClassId = "3";
      classExam(trainingClassId).then((res) => {
        const info = res.data;

        // 信息部分
        this.examInfo.title = info.name;
        this.examInfo.startTime = info.examStartTime;
        this.examInfo.endTime = info.examEndTime;
        this.examInfo.duration = info.examDuration;
        this.examInfo.trainingProject = info.trainingProjectName;
        this.examInfo.notice = info.examNotes;

        //存储提交接口所需id
        this.tempStudentId = info.studentId;
        this.tempExamPaperId = info.examPaperId;

        // 题目部分 - 根据题目类型分类
        if (info.questionList && Array.isArray(info.questionList)) {
          // 初始化题目数组
          this.singleQuestions = [];
          this.multipleQuestions = [];
          this.judgmentQuestions = [];

          // 遍历题目列表，根据题型分类
          info.questionList.forEach((question) => {
            // 转换选项格式
            let options = [];
            if (
              question.questionOptionList &&
              Array.isArray(question.questionOptionList)
            ) {
              options = question.questionOptionList.map((option) => ({
                id: option.optionId, // 使用唯一的optionId作为id
                value: option.optionName, // 使用optionName作为选项值(A,B,C,D)
                label: `${option.optionName}.${option.optionContent}`, // 组合显示: A.选项内容
              }));
            }

            switch (question.questionType) {
              case "1": // 单选题
                this.singleQuestions.push({
                  id: question.questionId,
                  text: question.questionName,
                  options: options,
                });
                break;

              case "2": // 多选题
                this.multipleQuestions.push({
                  id: question.questionId,
                  text: question.questionName,
                  options: options,
                });
                break;
              case "3": // 判断题
                this.judgmentQuestions.push({
                  id: question.questionId,
                  text: question.questionName,
                  options: question.options || [
                    { id: "true", value: "true", label: "对" },
                    { id: "false", value: "false", label: "错" },
                  ],
                });
                break;
            }
          });
        }
        // 获取完考试信息后---设置自动提交
        // this.setupAutoSubmit();

        this.$nextTick(() => {
          const savedAnswers = localStorage.getItem("examAnswers");
          if (savedAnswers) {
            this.userAnswers = JSON.parse(savedAnswers);
          }
        });
      });
    },
    submitExam() {
      // 整理单选题答案
      const singleAnswers = Object.entries(this.userAnswers.single).map(
        ([index, answer]) => ({
          questionId: this.singleQuestions[index].id,
          answer: answer,
        })
      );

      // 整理多选题答案
      const multipleAnswers = Object.entries(this.userAnswers.multiple).map(
        ([index, answers]) => ({
          questionId: this.multipleQuestions[index].id,
          answer: answers.join(","), // 多选答案用逗号连接
        })
      );

      // 整理判断题答案
      const judgmentAnswers = Object.entries(this.userAnswers.judgment).map(
        ([index, answer]) => ({
          questionId: this.judgmentQuestions[index].id,
          answer: answer,
        })
      );

      // 合并所有答案
      const allAnswers = [
        ...singleAnswers,
        ...multipleAnswers,
        ...judgmentAnswers,
      ];

      var params = {
        trainingClassId: "",
        studentId: this.tempStudentId,
        examPaperId: this.tempExamPaperId,
        questionAnswerList: allAnswers,
      };

      saveExamResult(params).then((res) => {
        // 清空本地存储的答案
        localStorage.removeItem("examAnswers");

        // 跳转到考试结果页面
        this.$router
          .push({
            name: "ExamResult",
            params: {
              score: res.data.score.toString(),
              // result: res.data.examResult === "1" ? "合格" : "不合格",
              // result: "合格",
              result: "不合格",
              canRetake: res.data.makeUpStatus === "1" ? true : false,
            },
          })
          .then(() => {
            console.log("路由跳转成功，当前路径:", this.$route.path);
          })
          .catch((err) => {
            console.error("路由跳转失败:", err);
          });
      });
    },
    //重置考试数据
    resetExamData() {
      // 清空考试信息
      this.examInfo = {};

      // 清空各类题目
      this.singleQuestions = [];
      this.multipleQuestions = [];
      this.judgmentQuestions = [];

      // 清空用户答案
      this.userAnswers = {
        single: {},
        multiple: {},
        judgment: {},
      };

      // // 清空临时ID
      // this.tempStudentId = null;
      // this.tempExamPaperId = null;
    },
    // 自动提交考试
    // // 计算距离考试结束的毫秒数
    // calculateTimeUntilEnd() {
    //   const endTime = new Date(this.examInfo.endTime).getTime();
    //   const now = new Date().getTime();
    //   return endTime - now;
    // },

    // // 设置自动提交
    // setupAutoSubmit() {
    //   const timeUntilEnd = this.calculateTimeUntilEnd();

    //   if (timeUntilEnd > 0) {
    //     // // 显示倒计时信息
    //     // this.timeRemaining = timeUntilEnd;
    //     this.updateCountdown(); // 启动倒计时更新

    //     this.examTimer = setTimeout(() => {
    //       this.submitExam();
    //     }, timeUntilEnd);
    //   } else {
    //     // 如果已经超过了结束时间，立即提交
    //     this.submitExam();
    //   }
    // },
    // // 更新倒计时显示
    // updateCountdown() {
    //   if (this.timeRemaining > 0) {
    //     // 计算剩余时间的小时、分钟、秒
    //     const hours = Math.floor(this.timeRemaining / (1000 * 60 * 60));
    //     const minutes = Math.floor(
    //       (this.timeRemaining % (1000 * 60 * 60)) / (1000 * 60)
    //     );
    //     const seconds = Math.floor((this.timeRemaining % (1000 * 60)) / 1000);

    //     console.log(
    //       `距离考试结束还有: ${hours}小时 ${minutes}分钟 ${seconds}秒`
    //     );

    //     // 每秒更新一次倒计时
    //     this.timeRemaining -= 1000;
    //     setTimeout(() => {
    //       this.updateCountdown();
    //     }, 1000);
    //   }
    // },
  },
  watch: {
    // 监听路由变化-----开始补考时重置内容
    $route(to, from) {
      // 当路由变化且包含补考标识时，重置考试数据
      if (to.query.retake === "true") {
        this.resetExamData();
        // 重新加载考试数据
        this.loadExamData();
      }
    },
    // beforeDestroy() {
    //   //清除定时器
    //   if (this.examTimer) {
    //     clearTimeout(this.examTimer);
    //   }
    // },
  },
};
</script>

<style scoped>
.exam-page {
  font-family: Arial, sans-serif;
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.exam-header {
  text-align: center;
  border-bottom: 1px solid #ddd;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

.exam-header h1 {
  margin: 0;
  color: #333;
}

.exam-info {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 30px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.info-item span:first-child {
  font-weight: bold;
  color: #666;
}

.exam-content {
  margin-bottom: 30px;
}

.question-section {
  margin-bottom: 30px;
}

.question-section h3 {
  margin-top: 0;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.question-item {
  margin-bottom: 20px;
}

.question-text {
  font-weight: bold;
  margin-bottom: 10px;
}

.options {
  margin-left: 20px;
}

.option-label {
  display: block;
  margin-bottom: 10px;
  cursor: pointer;
}

.option-label input {
  margin-right: 8px;
}

.submit-container {
  text-align: center;
  margin-top: 40px;
}

.submit-btn {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 12px 30px;
  font-size: 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.submit-btn:hover {
  background-color: #0056b3;
}
</style>


